const chalk = require('chalk');
const path = require('path')
const fs = require('fs');
const reslove = file => path.resolve(__dirname, '../', file)
// 获取文件路径
const RouterSymbol = reslove('src/router')
const ViewsSymbol = reslove('src/views')
const apiSymbol = reslove('src/api')

const vueFile = (module, dir, fileName) => {
    let upperDir = ""
    let perimisionPre = ""
    let reg = /\\|\//
    let dircopy = dir
    if (dir.indexOf('_') > -1) {
        let a = dir.split('_')
        let c = ""
        for (let i = 0; i < a.length; i++) {
            c += caseUpper(a[i])
        }
        dir = c
    }
    if (reg.test(dir)) {
        let arr = dir.split(reg)
        for (let i = 0; i < arr.length; i++) {
            upperDir += caseUpper(arr[i])
        }
        perimisionPre = module + ":" + arr.join(":")
    } else {
        upperDir = caseUpper(dir)
        perimisionPre = module + ":" + dir
    }
    let upperFileName = fileName.replace(/\b\w+\b/g, function (word) {
        return word.substring(0, 1).toUpperCase() + word.substring(1);
    });
    let tempPath = path.join(__dirname, 'templates/index.vue.tpl')
    let content = fs.readFileSync(tempPath, 'utf8').replace(/{module}/gi, module)
    content = content.replace(/{dir}/gi, dircopy)
    content = content.replace(/{fileName}/gi, fileName)
    content = content.replace(/{upperFileName}/gi, upperFileName)
    content = content.replace(/{upperDir}/gi, upperDir)
    content = content.replace(/{perimisionPre}/gi, perimisionPre)
    return content
}

const confFile = (module, dir, fileName) => {
    let tempPath = path.join(__dirname, `templates/${fileName}.js.tpl`)
    let content = fs.readFileSync(tempPath, 'utf8')
    return content
}

const caseUpper = function (str) {
    let upperStr = str.replace(/\b\w+\b/g, function (word) {
        return word.substring(0, 1).toUpperCase() + word.substring(1);
    });
    return upperStr
}

const apiFile = (module, dir,fileName) => {
    let reg = /\\|\//
    let upperDir = ""
    if (dir.indexOf('_') > -1) {
        let a = dir.split('_')
        let c = ""
        for (let i = 0; i < a.length; i++) {
            c += caseUpper(a[i])
        }
        dir = c
    }
    if (reg.test(dir)) {
        let arr = dir.split(reg)
        for (let i = 0; i < arr.length; i++) {
            upperDir += caseUpper(arr[i])
        }
    } else {
        upperDir = caseUpper(dir)
    }
    let upperFileName = fileName.replace(/\b\w+\b/g, function (word) {
        return word.substring(0, 1).toUpperCase() + word.substring(1);
    });
    let tempPath = path.join(__dirname, 'templates/index.js.tpl')
    let content = fs.readFileSync(tempPath, 'utf8')
        .replace(/{module}/gi, module)
        .replace(/{dir}/gi, dir)
        .replace(/{upperDir}/gi, upperDir)
        .replace(/{fileName}/gi, fileName)
        .replace(/{upperFileName}/gi, upperFileName)
    return content
}

const rl = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

// 递归创建目录 同步方法
const mkdirsSync = function (dirname) {
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true;
        }
    }
}


/**
 * 生成文件函数
 * @param {*} filePath 文件路径
 * @param {*} content 文件内容
 */
const generateFile = async (filePath, content) => {
    try {
        // 从filepath中分解出dirpath
        let dirPath = filePath.split("\\").slice(0, -1).join("\\")
        // defaultTig(mkdirsSync(dirPath));
        // return;
        // 判断dirpath是否存在
        if (dirPath !== '' && !await fs.existsSync(dirPath)) {
            let r = mkdirsSync(dirPath);
            if (r) {
                yellowTig(`创建目录 ${dirPath} 成功！`);
            }
        }
        // 判断 filepath是否存在
        if (!await fs.existsSync(filePath)) {
            // create file
            await fs.openSync(filePath, 'w')
            successTig(`创建文件 ${filePath} 成功！`)
            // console.log(typeof content)
            await fs.writeFileSync(filePath, content, 'utf8')
        } else {
            defaultTig(`${filePath}已存在！`)
            // process.stdin.emit('confirm')
        }
        // await fs.writeFileSync(filePath, content, 'utf8')
        // 向filepath中写入内容

    } catch (error) {
        errorTig(error)
    }
}

// map存储要创建的文件信息
const generates = new Map([
    ['view', async (module, dir, fileName) => {
        // const filePath = path.join(ViewsSymbol, module)
        const vuePath = path.join(ViewsSymbol, `${module}/${dir}/${fileName}.vue`)
        // vueFile(module)
        await generateFile(vuePath, vueFile(module, dir, fileName))
    }],
    ['router', async (module) => {
        const routerPath = path.join(RouterSymbol, `${module}/index.js`)
        await generateFile(routerPath, routerFile(module))
    }],
    ['conf', async (module, dir,fileName) => {
        // const filePath = path.join(ViewsSymbol, module)
        // const formConf = path.join(ViewsSymbol, `${module}/${dir}/conf/formConf.js`)
        // const tableConf = path.join(ViewsSymbol, `${module}/${dir}/conf/tableConf.js`)
        const config = path.join(ViewsSymbol, `${module}/${dir}/conf/config.js`)
        // vueFile(module)
        // await generateFile(formConf, confFile(module, dir, 'formConf'))
        // await generateFile(tableConf, confFile(module, dir, 'tableConf'))
        await generateFile(config, confFile(module, dir, 'config'))
    }],
    ['api', async (module, dir,fileName) => {
        let s = /\/|\\/
        let r = dir.split(s)
        let p = module + '/'
        for (let i = 0; i < r.length; i++) {
            p = p + r[i] + '/'
        }
        p = p + fileName + '.js'
        const apiPath = path.join(apiSymbol, p)
        await generateFile(apiPath, apiFile(module, dir,fileName))
    }]
])

const successTig = (msg) => console.log(chalk.green(msg));
const defaultTig = (msg) => console.log(chalk.white(msg));
const errorTig = (msg) => console.log(chalk.red(msg));
const yellowTig = (msg) => console.log(chalk.yellow(msg));
const question = (query) => new Promise(resolve => rl.question(query, (answer) => resolve(answer)));

const files = ['view', 'api','conf'];
(async () => {
    let module = await question("请输入Module:");
    successTig(`将创建的模块名是${module}`);
    let dir = await question("文件夹名称:");
    successTig(`文件夹名:${dir}`);
    let fileName = await question("文件名:")
    successTig(`文件名:${fileName}`);
    // let preAcc = await question("权限前缀：")
    // successTig(`权限前缀:（${preAcc}）`);

    files.forEach(async (el, index) => {
        await generates.get(`${el}`)(module, dir, fileName)
        if (index === files.length - 1) {
            rl.close();
        }
    })
})();
